package cn.easier.activity.console.controller;

import cn.easier.activity.console.entity.ActivityConsoleUser;
import cn.easier.activity.console.entity.ActivityRoleUser;
import cn.easier.activity.console.service.ActivityConsoleUserService;
import cn.easier.activity.console.service.ActivityInfoService;
import cn.easier.activity.web.entity.ActivityInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;
import java.util.function.Consumer;

public class BaseController {

    @Autowired
    ActivityInfoService activityInfoService;
    @Autowired
    ActivityConsoleUserService userService;

    public ActivityConsoleUser getPrincipal() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        ActivityConsoleUser activityConsoleUser;
        if (principal instanceof ActivityConsoleUser) {
            activityConsoleUser = (ActivityConsoleUser) principal;
        } else {
            activityConsoleUser = null;
        }
        return activityConsoleUser;
    }

    public boolean isAdmin(){
        ActivityConsoleUser principal = getPrincipal();
        String authoritiesStr = principal.getAuthoritiesStr();
        return authoritiesStr.equals("ROLE_USER_SUPERADMIN") || authoritiesStr.equals("ROLE_USER_ADMIN");
    }

    /**
     * 如果用户不是admin权限，获取当前用户名
     */
    public void ifNotAdmin(Consumer<String> consumer) {
        ActivityConsoleUser principal = getPrincipal();
        String user = principal.getUsername();
        String authoritiesStr = principal.getAuthoritiesStr();
        if (!authoritiesStr.equals("ROLE_USER_SUPERADMIN") && !authoritiesStr.equals("ROLE_USER_ADMIN")) {
            consumer.accept(user);
        }
    }

    public ActivityRoleUser getRole(){
        ActivityConsoleUser principal = getPrincipal();
        String user = principal.getUsername();
        return userService.getUserRole(user);
    }

    /**
     * 获取当前登陆用户名
     */
    public void getUser(Consumer<String> consumer) {
        ActivityConsoleUser principal = getPrincipal();
        String user = principal.getUsername();
        consumer.accept(user);
    }

    public ActivityInfo getActivityInfo(String authoritiesStr,String user,Integer activityInfoId) {
        ActivityInfo activityInfo = null;
        if (authoritiesStr.equals("ROLE_USER_SUPERADMIN") || authoritiesStr.equals("ROLE_USER_ADMIN")) {
            activityInfo = activityInfoService.findByOne(activityInfoId);
        } else {
            activityInfo = activityInfoService.findOne(activityInfoId, user);
        }
        return activityInfo;
    }
}
